<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\AuthorizationsRequest;
use App\Http\Requests\Api\AuthRequest;
use Illuminate\Http\Request;
use App\Models\User;

class AuthorizationsController extends Controller
{
    //
    public function store(AuthRequest $request)
    {
        //传入两个参数username,password.这里username 可能有是邮箱或者电话,需要判断一下
        $username = $request->username;
        filter_var($username, FILTER_VALIDATE_EMAIL) ? $credentials['email'] = $username : $credentials['phone'] = $username;
        $credentials['password'] = $request->password;
        $token = \Auth::guard('api')->attempt($credentials);
        if (!$token) {
            return $this->response->errorUnauthorized('用户名密码不正确');
        }
        //这里定义一个通用的返回信息函数
        return $this->authResult($token)->setStatusCode(200);
    }

    /**微信oauth 登录
     * @param $type 路由中的第三方登录类型参数,如weixin
     * @param AuthorizationsRequest $request
     */
    public function weiXinLogin($type, AuthorizationsRequest $request)
    {
        if (!in_array($type, ['weixin'])) {
            return $this->response->errorBadRequest();
        }
        $driver = \Socialite::driver($type);
        try {
            /*如果传递是code*/
            if ($code = $request->code) {
                $response = $driver->getAccessTokenResponse($code);
                $token = array_get($response, 'access_token');
            } else {
                $token = $request->access_token;
                if ($type == 'weixin') {
                    $driver->setOpenId($request->openid);
                }
            }
            $oauthUser = $driver->userFromToken($token);
        } catch (\Exception $e) {
            return $this->response->errorUnauthorized('参数错误');
        }
        /*根据获取的用户信息,去数据库中查找,如果存在则将查询结果返回,否则新建数据并返回*/
        switch ($type) {
            case 'weixin':
                $unionid = $oauthUser->offsetExists('unionid') ? $oauthUser->offsetGet('unionid') : null;
                if ($unionid) {
                    /*如果有unionid则用unionid查询,否则用openid查询*/
                    $user = User::where('weixin_unionid', $unionid)->first();
                } else {
                    $user = User::where('weixin_openid', $oauthUser->getId())->first();
                }
                if (!$user) {
                    $user = User::create([
                        'name' => $oauthUser->getNickname(),
                        'avatar' => $oauthUser->getAvatar(),
                        'wenxin_opeinid' => $oauthUser->getId(),
                        'weixin_unionid' => $unionid,
                    ]);
                }
                break;
        }
        //这里临时先返回id值
        $token = \Auth::guard('api')->fromUser($user);
        return $this->authResult($token)->setStatusCode(200);
    }

    public function refresh()
    {
        $token=\Auth::guard('api')->refresh();
        return $this->authResult($token)->setStatusCode(200);
    }

    public function destroy()
    {
        \Auth::guard('api')->logout();
        return $this->response->noContent();
    }

    protected function authResult($token)
    {
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
        ]);
    }
}
